package tp.pr5.instructions;

import tp.pr5.Constants;
import tp.pr5.NavigationModule;
import tp.pr5.RobotEngine;
import tp.pr5.instructions.exceptions.InstructionExecutionException;
import tp.pr5.instructions.exceptions.WrongInstructionFormatException;
import tp.pr5.items.Item;
import tp.pr5.items.ItemContainer;

/**
 * The Instruction for using an item. This Instruction works if the user writes OPERATE id or OPERAR id
 *
 */
public class OperateInstruction implements Instruction
{

	private RobotEngine engine;
	private NavigationModule navigation;
	private ItemContainer robotContainer;
	private String id;
	
	/**
	 * Default constructor
	 */
	public OperateInstruction()
	{
		this.engine = null;
		this.navigation = null;
		this.robotContainer = null;
	}
	
	/**
	 * Constructor with id
	 * @param id id of the item
	 */
	public OperateInstruction(String id)
	{
		this();
		this.id = id;
	}

	/**
	 * Parses the String returning an instance of OperateInstruction or throwing a WrongInstructionFormatException()
	 * 
	 * @param cad string given
	 */
	@Override
	public Instruction parse(String cad) throws WrongInstructionFormatException 
	{
		String[] entry = cad.toUpperCase().trim().split(" +");
		if((entry[0].equals("OPERATE") || entry[0].equals("OPERAR")) && entry.length == 1)
		{
			throw new WrongInstructionFormatException(); 
		}
		if((entry[0].equals("OPERATE") || entry[0].equals("OPERAR")) && entry.length == 2)
		{
			return new OperateInstruction(entry[1]);
		}
		throw new WrongInstructionFormatException();
	}

	/**
	 * Fixes the current context, i.e., the robot engine and the navigation module
	 * 
	 * @param engine RobotEngine
	 * @param navigation NavigationModule
	 * @param robotContainer ItemContainer
	 * 
	 */
	@Override
	public void configureContext(RobotEngine engine, NavigationModule navigation, ItemContainer robotContainer)
	{
		this.engine = engine;
		this.navigation = navigation;
		this.robotContainer = robotContainer;
	}

	/**
	 * The robot uses the requested item.
	 */
	@Override
	public void execute() throws InstructionExecutionException
	{
		
		try
		{
			Item item = this.robotContainer.getItem(this.id);
			
			if(item != null)
			{
				if(item.use(this.engine, this.navigation))
				{
					this.robotContainer.useItem(item);
				}
				else 
				{
					throw new InstructionExecutionException(Constants.MESSAGE_CHANGES_ERROR.replace("{ID}", this.id));
				}
			}
			else
			{
				throw new InstructionExecutionException(Constants.MESSAGE_TRY_USE_ITEM_BUT_NOT_EXISTS.replace("{ID}", this.id));
			}
			
		} catch(Exception e){
			throw e;
		}
	}

	/**
	 * Returns a description of the Instruction syntax. The string does not end with the line separator. It is up to the caller adding it before printing.
	 */
	@Override
	public String getHelp() 
	{
		return "OPERATE|OPERAR <id>";
	}

}
